package com.itany.corejava.day18;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过Class对象访问类信息
public class TestClass3 {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        Class c=Person.class;

        //调用无参构造方法创建对象
        Person p1= (Person) c.newInstance();

        System.out.println("p1 = " + p1);

        //调用有参构造方法创建对象
        Constructor con=c.getDeclaredConstructor(String.class,int.class,boolean.class);
        Person p2= (Person) con.newInstance("abc",21,true);

        System.out.println("p2 = " + p2);

        //访问属性
        Field f=c.getDeclaredField("age");
        f.setAccessible(true);
        System.out.println("f.get(p2) = " + f.get(p2));
        f.set(p1,53);
        System.out.println("p1.getAge() = " + p1.getAge());

        //访问方法
        Method m1=c.getDeclaredMethod("fn1");
        m1.setAccessible(true);
        System.out.println(m1.invoke(p1));

        Method m2=c.getDeclaredMethod("fn2",int.class);
        int result= (int) m2.invoke(p1,3);
        System.out.println(result);

        Method m3=c.getDeclaredMethod("fn3");
        m3.invoke(null);


    }
}
